class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

/**
 *230. 二叉搜索树中第K小的元素
 * https://leetcode.cn/problems/kth-smallest-element-in-a-bst/description/
 */
class Solution {
    int ret = 0;
    int count = 0;
    public int kthSmallest(TreeNode root, int k) {
        count = k;
        dfs(root);
        return ret;
    }
    public void dfs(TreeNode root) {
        if(root == null || count <= 0) return;//后面是剪枝，控制left的
        dfs(root.left);
        //if(count <= 0) return;//剪枝
        count--;
        if(count == 0) {
            ret = root.val;
            return;//这里也是剪枝，控制right的
        }
        dfs(root.right);
    }
}